package com.fzl.spring_chatroom.controller;

import com.fzl.spring_chatroom.model.dao.User;
import com.fzl.spring_chatroom.model.request.UserLoginRequest;
import com.fzl.spring_chatroom.model.request.UserRegisRequest;
import com.fzl.spring_chatroom.model.response.UserInfoResponse;
import com.fzl.spring_chatroom.model.response.UserLoginResponse;
import com.fzl.spring_chatroom.service.UserService;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    @RequestMapping("/login")
    public UserLoginResponse login(@RequestBody UserLoginRequest userLoginRequest, HttpSession session) {
        log.info("用户名：" + userLoginRequest.getUsername());
        return userService.checkPassword(userLoginRequest);
    }

    @RequestMapping("/register")
    public Boolean register(@RequestBody @Validated UserRegisRequest userRegisterRequest) {
        log.info("用户注册信息" + userRegisterRequest);
        return userService.register(userRegisterRequest);
    }

    @RequestMapping("/getuser")
    public UserInfoResponse getUserResponse(Integer userId) {
        log.info("用户名：" + userId);
        return userService.getUser(userId);
    }

    @GetMapping("/search")
    public UserInfoResponse searchUser(String keyword) {
        User user = userService.searchUser(keyword);
        if (user == null)
            return null;
        String avatar = (user.getAvatar() == null || user.getAvatar().isEmpty()) ? "/avatar/default.png"
                : user.getAvatar();
        return new UserInfoResponse(user.getUserId(), user.getUsername(), avatar);
    }
}
